package com.newtribe.security;

import java.security.cert.CertificateFactory;
import java.io.* ;
import java.security.cert.X509Certificate;
import java.security.Principal;
import java.util.*;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import sun.security.x509.X500Name;
import sun.security.x509.CertificateIssuerName;
/**
 * <p> </p>
 * <p>Description: Certificate read/write operation </p>
 * <p>Copyright: Copyright (c)  newtribe innovation 2005</p>
 * <p> </p>
 * @author fuwei
 * @version 1.0
 */

public class CertificateTest {
  public CertificateTest() {
  }
  
  static void validParentCert() throws Exception {
	    CertificateFactory certFactory = CertificateFactory.getInstance("X.509") ;
	    InputStream parent =new FileInputStream("D:/ca/p10test/root.cer") ;
	     X509Certificate root =  (X509Certificate)certFactory.generateCertificate(parent) ;
	  
	     
		    InputStream response =new FileInputStream("D:/ca/p10test/response.cer") ;
		     X509Certificate sub =  (X509Certificate)certFactory.generateCertificate(response) ;
		     
		  //   root.verify(sub.getPublicKey());
		     sub.verify(root.getPublicKey());
	  
  }
  public static void main(String[] args) throws Exception{
	  
	  validParentCert();
	  

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509") ;


    InputStream in =new FileInputStream("d:/ww.cer") ;

     X509Certificate x =  (X509Certificate)certFactory.generateCertificate(in) ;

     X509CertImpl scert = null ;


    String dn =x.getSubjectDN().toString();


    String sd =new String(dn.getBytes("ISO-8859-1"),"UTF-8");
     String s = x.getSerialNumber().toString();
     Principal issuerdn =   x.getIssuerDN() ;
      Principal subject = x.getSubjectDN() ;
      HashMap result =parseDN(subject.toString()) ;
      System.out.println(result);
     System.out.println(x);

  }


  public static HashMap parseDN(String dnStr) {

  if (dnStr == null)
    return null;
  StringTokenizer token = new StringTokenizer(dnStr, ",");
  HashMap result = new HashMap();
  while (token.hasMoreElements()) {
    String str = (String) token.nextElement();

    String[] s = str.split("=");
    if (s != null && s.length == 2 && s[0] != null && s[1] != null)
      result.put(s[0].trim(), s[1].trim());
  }

  return result;
}


}
